package com.ycy.temperature.view.fragment;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.jude.utils.JUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ycy.temperature.R;
import com.ycy.temperature.adapter.GridViewAdapter;
import com.ycy.temperature.adapter.ViewPagerAdapter;
import com.ycy.temperature.bean.BannerBean;
import com.ycy.temperature.bean.VipListBean;
import com.ycy.temperature.date.net.UserNetWorks;
import com.ycy.temperature.view.base.BaseFragment;
import com.ycy.temperature.view.view.BGABanner;
import com.ycy.temperature.view.view.MyViewPager;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Subscriber;


public class HomePageFragment extends BaseFragment implements BGABanner.Delegate<ImageView, BannerBean.DataBean>, BGABanner.Adapter<ImageView, BannerBean.DataBean> {
    @BindView(R.id.banner)
    BGABanner banner;
    Unbinder unbinder;
    @BindView(R.id.Layout_Schedule)
    AutoLinearLayout LayoutSchedule;
    @BindView(R.id.viewpager)
    MyViewPager viewpager;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;

    int pageSize = 9;
    int curIndex = 0;
    String StrPage = "1";
    List<View> mPagerList;
    LayoutInflater inflater;
    DynamicFragment dynamicFragment;
    ActivityFragment activityFragment;
    @BindView(R.id.Text_Activity)
    TextView TextActivity;
    @BindView(R.id.Text_Dynamic)
    TextView TextDynamic;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    @Override
    protected int getRes() {
        return R.layout.fragment_homepage;
    }

    @Override
    protected void init(View view) {
        unbinder = ButterKnife.bind(this, view);
        banner.setDelegate(this);
        inflater = LayoutInflater.from(getActivity());
        mPagerList = new ArrayList<>();

        dynamicFragment = new DynamicFragment();
        activityFragment = new ActivityFragment();
        getActivity().getSupportFragmentManager().beginTransaction().add(R.id.Layout_Page, activityFragment).disallowAddToBackStack().commit();
        getActivity().getSupportFragmentManager().beginTransaction().add(R.id.Layout_Page, dynamicFragment).disallowAddToBackStack().show(dynamicFragment).commit();
        dynamicFragment.hide();
        getBanner();
        getVipList();
        getsmartRefreshLayout();
    }

    @OnClick({R.id.Text_Activity, R.id.Text_Dynamic})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.Text_Activity:
                StrPage = "1";
                showFragment(activityFragment);
                TextActivity.setTextColor(TextActivity.getResources().getColor(R.color.bg_Blue));
                TextDynamic.setTextColor(TextDynamic.getResources().getColor(R.color.tx_Gray));
                break;
            case R.id.Text_Dynamic:
                StrPage = "2";
                TextDynamic.setTextColor(TextActivity.getResources().getColor(R.color.bg_Blue));
                TextActivity.setTextColor(TextDynamic.getResources().getColor(R.color.tx_Gray));
                showFragment(dynamicFragment);
                break;
        }
    }

    public void getsmartRefreshLayout() {
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (StrPage.equals("1")) {
                            activityFragment.i = 0;
                            activityFragment.setActivity("0");
                            refreshLayout.finishRefresh();
                        } else if (StrPage.equals("2")) {
                            dynamicFragment.i = 0;
                            dynamicFragment.setDynamic("0");
                            refreshLayout.finishRefresh();
                        }
                    }
                }, 2000);
            }
        });
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (StrPage.equals("1")) {
                            activityFragment.setActivity(activityFragment.i + "");
                            refreshLayout.finishLoadMore();
                        } else if (StrPage.equals("2")) {
                            dynamicFragment.setDynamic(dynamicFragment.i + "");
                            refreshLayout.finishLoadMore();
                        }

                    }
                }, 2000);
            }
        });
    }

    public void showFragment(Fragment showFragemt) {
        hideFrags();
        getActivity().getSupportFragmentManager().beginTransaction().disallowAddToBackStack().show(showFragemt).commit();
    }

    public void hideFrags() {
        dynamicFragment.hide();
        activityFragment.hide();
    }

    public void getBanner() {
        UserNetWorks.getBanner("1", new Subscriber<BannerBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(BannerBean bannerBean) {
                if (bannerBean.getResponseState().equals("1")) {
                    if (bannerBean.getData().size() > 0) {
                        banner.setAutoPlayAble(bannerBean.getData().size() > 1);
                        banner.setAdapter(HomePageFragment.this);
                        if (bannerBean.getData() != null) {
                            banner.setData(bannerBean.getData(), null);
                        }
                    }
                }
            }
        });
    }

    public void getVipList() {
        UserNetWorks.getVipList("1", new Subscriber<VipListBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                JUtils.Toast("网络错误");
            }

            @Override
            public void onNext(final VipListBean vipListBean) {
                if (vipListBean.getResponseState().equals("1")) {
                    for (int i = 0; i < (int) Math.ceil(vipListBean.getData().size() * 1.0 / pageSize); i++) {
                        //每个页面都是inflate出的一个新实例
                        GridView gridView = (GridView) inflater.inflate(R.layout.gridview, null);
                        gridView.setAdapter(new GridViewAdapter(getActivity(), vipListBean.getData(), i, pageSize));
                        mPagerList.add(gridView);
                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                int pos = position + curIndex * pageSize;
                                Toast.makeText(getActivity(), vipListBean.getData().get(pos).getNickname(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    //设置viewpageAdapter
                    viewpager.setAdapter(new ViewPagerAdapter(mPagerList));
                    setOvalLayout((int) Math.ceil(vipListBean.getData().size() * 1.0 / pageSize));
                }
            }
        });
    }

    private void setOvalLayout(int pageCount) {
        for (int i = 0; i < pageCount; i++) {
            LayoutSchedule.addView(inflater.inflate(R.layout.dot, null));
        }
        //默认显示第一页
        LayoutSchedule.getChildAt(0).findViewById(R.id.v_dot).setBackgroundResource(R.drawable.dot_selected);
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                //取消选中
                LayoutSchedule.getChildAt(curIndex).findViewById(R.id.v_dot).setBackgroundResource(R.drawable.dot_normal);
                //选中
                LayoutSchedule.getChildAt(position).findViewById(R.id.v_dot).setBackgroundResource(R.drawable.dot_selected);

                curIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public void onBannerItemClick(BGABanner banner, ImageView itemView, @Nullable BannerBean.DataBean model, int position) {
//        Intent intent = new Intent(mContext, HomePageActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putString("title", model != null ? model.getTitle() : null);
//        bundle.putString("url", model != null ? model.getObject() : null);
//        intent.putExtras(bundle);
//        startActivity(intent);
    }

    @Override
    public void fillBannerItem(BGABanner banner, ImageView itemView, @Nullable BannerBean.DataBean model, int position) {
        Glide.with(getActivity())
                .load("http://" + model.getBannerpath())
                .apply(new RequestOptions()
                        .centerCrop()
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .diskCacheStrategy(DiskCacheStrategy.ALL))
                .into(itemView);
    }

    @Override
    protected void setData(View view) {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}